package com.up.upzl.biz.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.google.common.collect.Lists;
import com.up.upzl.base.service.impl.BaseServiceImpl;
import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.domain.SysRole;
import com.up.upzl.biz.repository.SysRoleRepository;
import com.up.upzl.biz.service.SysAppService;
import com.up.upzl.biz.service.SysRoleService;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole, Long> implements SysRoleService {

	@Autowired
	private SysRoleRepository sysRoleRepository;

	@Autowired
	private SysAppService sysAppService;

	@Override
	public Page<SysRole> findByCondition(String roleName, Pageable page) {
		return sysRoleRepository.findAll(new Specification<SysRole>() {

			@Override
			public Predicate toPredicate(Root<SysRole> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(roleName)) {
					predicates.add(cb.and(cb.like(cb.lower(root.get("roleName")), "%" + roleName.toLowerCase() + "%")));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}

	@Override
	public void associateSysApp(Long roleId, Long[] appIds) {
		SysRole sysRole = sysRoleRepository.findOne(roleId);
		List<SysApp> sysApps = Lists.newArrayList();
		sysApps.addAll(sysAppService.findAll(Arrays.asList(appIds)));
		sysRole.setSysApps(sysApps);
		sysRoleRepository.save(sysRole);
	}
}
